package cn.gym.controller;

import cn.gym.pojo.User;
import cn.gym.service.UserService;
import cn.gym.tools.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Resource
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/login.html",method = RequestMethod.GET)
    public String doLogin(){
        return "login";
    }
    @RequestMapping(value = "/login.html",method = RequestMethod.POST)
    public String doLogin(@RequestParam("userCode")String username,
                          @RequestParam("userpassword")String userpassword, HttpSession session){

        User user =new User();
        user.setUsercode(username);
        user.setPassword(userpassword);
        User loginUser=this.userService.doLoin(user);
        if(loginUser==null){
            throw new RuntimeException("用户名或密码不正确");
        }else {
            session.setAttribute(Constants.USER_SESSION,loginUser);
            return "redirect:/main.html";
        }
    }
    @RequestMapping("/main.html")
    public String main(HttpSession session){
        User user=(User)session.getAttribute(Constants.USER_SESSION);
        if(user!=null){
            if(user.getRoleid()==0){
                return "admin/index";
            }else if(user.getRoleid()==1){
                return "trainer/index";
            }else if(user.getRoleid()==2){
                return "customer/index";
            }else{
                throw new RuntimeException("系统内部错误，请重新登录！");
            }
        }else {
            return "401";
        }
    }
}
